package com.michael.study.bitmap

import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.BitmapRegionDecoder
import android.graphics.Rect
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.michael.study.bitmap.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity(), View.OnClickListener {

    private lateinit var mBinding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(mBinding.root)
        mBinding.btnIntent.setOnClickListener(this)
        mBinding.btnBinder.setOnClickListener(this)

    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.btn_intent -> {
                var intent = Intent(this,IPCBitmapActivity::class.java)
                intent.apply {
                    var bundle = Bundle()
                    bundle.putParcelable("bitmap",getBitmap())
                    putExtras(bundle)
                }
                startActivity(intent)
            }

            R.id.btn_binder -> {

                var intent = Intent(this,IPCBitmapActivity::class.java)
                intent.apply {
                    var bundle = Bundle()
                    putExtras(bundle)
                }
                startActivity(intent)

            }
        }
    }

    fun getBitmap(): Bitmap? {

        try {
            var inputStream = assets.open("ic_launcher.png")
            var bitmap = BitmapFactory.decodeStream(inputStream)
            Log.d("lgq", "getBitmap: " + bitmap.allocationByteCount / 1024)
            return bitmap
        } catch (e: java.lang.Exception) {
            return null
        }


    }

    /**
     * 按区域加载图片
     */
    fun showRegionImage() {
        try {
            var inputStream = assets.open("rodman3.png")
            var options = BitmapFactory.Options()
            options.inJustDecodeBounds = true
            BitmapFactory.decodeStream(inputStream, null, options)
            var width = options.outWidth;
            var height = options.outHeight;

            var regionDecoder = BitmapRegionDecoder.newInstance(inputStream, false);
            options.inJustDecodeBounds = false;
            options.inPreferredConfig = Bitmap.Config.RGB_565;
            var bitmap: Bitmap = regionDecoder.decodeRegion(
                Rect(
                    width / 2 - 200,
                    height / 2 - 200,
                    width / 2 + 200,
                    height / 2 + 200
                ), options
            )


        } catch (e: Exception) {

        }
    }

}
